package net.contrend.system.dao;

import java.sql.Types;
import java.util.List;
import java.util.UUID;

import org.springframework.jdbc.core.JdbcTemplate;

import net.contrend.system.form.RoleForm;
import net.contrend.system.mapper.RoleFormMapper;
import net.contrend.util.SqlUtils;
import net.contrend.util.StringUtils;

public class RoleDao extends BaseDao{
    
    private String table = "ct_role";

    public RoleDao() {
    }
    
    public RoleDao(JdbcTemplate jt) {
        this.jt = jt;
    }
    
    public int insert(RoleForm role) {
        String columns = "roleid, rolename, status, orderno, remark";
        String sql = SqlUtils.getInsertSql(this.table, columns);
        System.out.println(String.format("\n%1$s\n", sql));
        
        if (StringUtils.isBlank(role.getRoleId())) {
            role.setRoleId(UUID.randomUUID().toString());
        }
        
        return this.jt.update(sql,
                new Object[]{
                    role.getRoleId(),
                    role.getRoleName(),
                    role.getStatus(),
                    role.getOrderNo(),
                    role.getRemark()
                },
                new int[]{
                    Types.VARCHAR,
                    Types.VARCHAR,
                    Types.VARCHAR,
                    Types.INTEGER,
                    Types.VARCHAR
                });
    }
    
    public int update(RoleForm role) {
        String columns = "rolename, status, orderno, remark";
        String sql = SqlUtils.getUpdateSql(this.table, columns, "roleid = ?");
        System.out.println(String.format("\n%1$s\n", sql));
        
        return this.jt.update(sql,
                new Object[]{
                    role.getRoleName(),
                    role.getStatus(),
                    role.getOrderNo(),
                    role.getRemark(),
                    role.getRoleId()
                },
                new int[]{
                    Types.VARCHAR,
                    Types.VARCHAR,
                    Types.INTEGER,
                    Types.VARCHAR,
                    Types.VARCHAR
                });
    }
    
    public int delete(String id) {
        String sql = SqlUtils.getDeleteSql(this.table, "roleid = ?");
        System.out.println(String.format("\n%1$s\n", sql));
        return this.jt.update(sql, new Object[]{id}, new int[]{Types.VARCHAR});
    }
    
    @SuppressWarnings("unchecked")
    public RoleForm query(String id) {
        String sql = "select * from ct_role where roleid = ?";
        List<RoleForm> roleList = this.jt.query(sql,
                new Object[]{id}, new int[]{Types.VARCHAR}, new RoleFormMapper());
        if (null != roleList && 0 < roleList.size()) {
            return roleList.get(0);
        }
        return null;
    }
    
}
